<template>
<view>
  <timePicker ref="timePicker" @getTime='getTime'></timePicker>
  <view class="address-time-picker" @click="openVehConfig">
    <image class="edit-icon" src="https://taxi.raxan.xyz/wechat/static/images/edit-box-line.png" mode="" />
    <view class="store_name">{{ area.city_name + area.area_name }}</view>
    <view class="hire_time">
      <view class="time">{{ DateTime.starMon }}月{{ DateTime.starDay }}日 {{ DateTime.starTime }}</view>
      <view class="line"></view>
      <view class="time">{{ DateTime.endMon }}月{{ DateTime.endDay }}日 {{ DateTime.endTime }}</view>
    </view>
  </view>
  <uni-popup ref="popup" background-color="#fff" borderRadius="0rpx  0rpx  24rpx  24rpx">
    <view class="popup-container">
      <view class="picker-row">
        <view class="picker-row-title">
          <view @click="changeCity(1,'取车城市')">选择城市</view>
          <view @click="changeArea(1,'取车地点')">选择门店</view>
        </view>
        <view class="picker-row-content">
          <view @click="changeCity(1,'取车城市')"> {{area.city_name?area.city_name:'请选择城市'}} </view>
          <view @click="changeArea(1,'取车地点')" class="address"> {{area.area_name? area.area_name : '请选择地点'}} </view>
        </view>
      </view>
      <view class="picker-row" v-if="is_other_places">
        <view class="picker-row-title">
          <view @click="changeCity(2,'还车城市')">还车城市</view>
          <view @click="changeArea(2,'还车地点')">还车地点</view>
        </view>
        <view class="picker-row-content">
          <view @click="changeCity(2,'还车城市')"> {{area.black_city_name?area.black_city_name:'请选择城市'}} </view>
          <view @click="changeArea(2,'还车地点')" class="address"> {{area.black_area_name? area.black_area_name : '请选择地点'}} </view>
        </view>
      </view>
      <view class="select-time _flex-row-mid _mar-bottom-16">
        <view class="_flex-col-mid _pad-y-10" @click="showTimePicker(0)">
          <view class="_b _font-15 _mar-bottom-5">{{DateTime.starMon||0}} 月 {{DateTime.starDay||0}} 日</view>
          <view class="_font-14" style="color: rgba(0,0,0,0.9)">{{formatWeekAndTime('start')}}</view>
        </view>
        <view class="_flex-1 _flex-col-mid" style="align-self: center;">
          <view class="_font-14 _border-bottom" style="padding-bottom: 18rpx;color: rgba(0,0,0,0.9)">共{{DateTime.days}}</view>
        </view>
        <view class="_flex-col-mid _pad-y-15" @click="showTimePicker(1)">
          <view class="_b _font-15 _mar-bottom-5">{{DateTime.endMon||0}} 月 {{DateTime.endDay||0}} 日</view>
          <view class="_font-14" style="color: rgba(0,0,0,0.9)">{{formatWeekAndTime('end')}}</view>
        </view>
      </view>
      <view class="_flex-row-mid _pad-y-15 _font-13">
        <radio :checked="is_visit" @click="visit()" /><text class="_pad-right-5">上门送取车</text> <text class="btn-tips">需提前两小时预定</text>
      </view>
      <view class="_w-max _mar-bottom-10 _text-center _font-16 ">
        <view @click="toChooseCar(DateTime)" class="_w-max theme-color-bg  _pad-y-10" style="border-radius: 12rpx;color: #FFFFFF;">去选车</view>
      </view>
    </view>
  </uni-popup>
    
  <view class="_pos-rel container-page" v-if="false">
		<view class="_pad-x-15 _pos-rel _z-index-1" style="margin-top: -92rpx;">
			<view class="center_box">


				<view class="_flex-row-mid _pad-y-15 _font-13">
					<radio :checked="is_visit" @click="visit()" /><text class="_pad-right-5">上门送取车</text> <text class="btn-tips">需提前两小时预定</text>
				</view>
				<view class="_w-max _mar-bottom-10 _text-center _font-16 ">
					<view @click="toChooseCar(DateTime)" class="_w-max theme-color-bg  _pad-y-10" style="border-radius: 12rpx;color: #FFFFFF;">立即选车</view>
				</view>
			</view>
		</view>
	</view>
</view>
  
</template>

<script>
	import timePicker from '@/pages/car_index/handler/timePicker.vue';
	import { disposeTime, isCityOpen } from '@/api/car.js'

	export default{
    props: {
      dir: {
        type: String,
        default: 'top'
      },
      dataSiteInfo: {
        type: Object,
        default: () => ({})
      },
      noClick:{
        type:Boolean,
        default:false
      }
    },
    watch: {
      dataSiteInfo: {
        deep: true,
        handler(newParams) {
          this.is_visit = newParams.is_visit;
          this.is_other_places = newParams.is_other_places;

          Object.keys(this.vehModeConf).forEach(key => {
            this.vehModeConf[key] = this.vehModeConf[key] || newParams[key]
          })

          Object.keys(this.area).forEach(key => {
            this.area[key] = newParams.areaInfo[key]
          })

          Object.keys(this.DateTime).forEach(key => {
            this.DateTime[key] = newParams[key]
          })
        }
      }
    },
		components:{
			timePicker
		},
		data(){
			return{
				is_other_places:false, //是否异店还车
				is_visit:false,//是否上门送取车
				area_list:[],//取车地点列表
        vehModeConf: {
          is_store_take: 0, // 	是否门店自取
          is_door_take: 0, // 是否上门取车
          is_free: 0
        },
				//省、市
				area:{
					area_id:0,
					area_name:'',
					city_id:0,
					city_name:'',
					latitude:0,
					longitude:0,
					black_area_id:0,
					black_area_name:'',
					black_city_id:0,
					black_city_name:'',
					black_latitude: 0,
					black_longitude: 0,
				},
				DateTime:{
					days:'1天', //两日期相差的天数
					day:0,//天数
					hour:0,//小时数
					starStamp:null,//取车时间（时间戳）
					endStamp:null,//还车时间（时间戳）
					starMon:null, //取车月份
					endMon:null,//还车月份
					starDay:null, //取车日
					endDay:null,//还车日
					starTime:null,//取车时间
					endTime:null,//还车时间
					end_time:'',//还车时间日期列表
					start_time:'',//取车时间日期列表
				}
			};
		},
		onShareAppMessage() {
			
		},
		methods:{
      setData(newParams) {
        this.is_visit = newParams.is_visit;
        this.is_other_places = newParams.is_other_places;

        Object.keys(this.vehModeConf).forEach(key => {
          this.vehModeConf[key] = this.vehModeConf[key] || newParams[key]
        })

        Object.keys(this.area).forEach(key => {
          this.area[key] = newParams.areaInfo[key]
        })

        Object.keys(this.DateTime).forEach(key => {
          this.DateTime[key] = newParams[key]
        })
      },
      openVehConfig() {
        if(this.noClick) return
        const dir = this.dir || 'top';
        this.$refs.popup.open(dir);
      },
      closeVehConfig() {
        this.$refs.popup.close();
      },
			formatWeekAndTime(type) {
				const weekList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
				const { starStamp, endStamp, starTime, endTime } = this.DateTime;
				const stamp = type === 'start' ? starStamp : endStamp;
				const date = new Date(stamp);
				const index = !stamp ? -1 : date.getDay();
				const time = (type === 'start' ? starTime : endTime) || '00:00';

				let r_week = index > -1 ? weekList[index] : '';
				const new_date = new Date();
				
				if (
					date.getFullYear() === new_date.getFullYear() &&
					date.getMonth() === new_date.getMonth() &&
					date.getDate() === new_date.getDate()
				) {
					r_week = '今日'
				}

				return `${r_week}${time}`;
			},
			// 修改是否异点还车
			changeSwitch(){
				this.area={
					area_id:0,
					area_name:'',
					city_id:0,
					city_name:'',
					black_area_id:0,
					black_area_name:'',
					black_city_id:0,
					black_city_name:'',
				}
				this.is_other_places = !this.is_other_places;
				this.is_visit = this.is_other_places;
				this.area.is_other_places = this.is_other_places;
				this.area.is_visit = this.is_visit;
			},
			visit(){
				this.is_visit = !this.is_visit;
				// this.is_other_places = this.is_visit?true:this.is_other_places;
				this.is_other_places = this.is_visit?true:false;
        if (this.is_visit) {
          this.backup_area = { ...this.area }
          this.area={
            area_id:0,
            area_name:'',
            city_id:0,
            city_name:'',
            black_area_id:0,
            black_area_name:'',
            black_city_id:0,
            black_city_name:'',
          }
        } else {
          this.area = {
            ...this.backup_area
          }
        }

				this.area.is_other_places = this.is_other_places;
				this.area.is_visit = this.is_visit;
			},
			//选择城市
			changeCity(type,title){
				let that = this;
				let param = {};
				param.title = title;
				// #ifdef MP-WEIXIN
				if(this.is_visit){
					wx.chooseLocation({
						success (res) {
							const address = res.address;
							let reg = /.+?(省|市|自治区|自治州|县|区)/g;
							let city = address.match(reg)[1];
							const name = res.name;
							const latitude = res.latitude; //纬度
							const longitude = res.longitude; //经度
							isCityOpen({city_name: city}).then((res)=>{
								if(type==1){// 选择取车城市、地点
									that.area.city_id = res.data.id
									that.area.city_name = city;
									that.area.area_name = name;
									that.area.latitude = latitude;
									that.area.longitude = longitude;
								}else{// 选择还车城市、地点
									that.area.black_city_id = res.data.id
									that.area.black_city_name = city;
									that.area.black_area_name = name;
									that.area.black_latitude = latitude;
									that.area.black_longitude = longitude;
								}
							}).catch((err)=>{
								return uni.showToast({ title:err, icon:'none' })
							})
						},fail(res){
							console.log(res)
						}
					})
					return;
				}
				//#endif
				uni.navigateTo({
					url:`/pages/car_sub/address_list/index?param=${JSON.stringify(param)}`,
					events:{
						getCity(option){
							if(type == 1){// 选择取车城市
								that.area.city_name = option.label;
								that.area.city_id = option.value;
								that.area.area_name = '';
								that.area.area_id = 0;
							}else{// 选择还车城市
								that.area.black_city_name = option.label;
								that.area.black_city_id = option.value;
								that.area.black_area_name = '';
								that.area.black_area_id = 0;
							}
							// uni.setStorageSync('ADDRESS',that.area)
						},
					},
				})
			},
			//选择地点
			changeArea(type,title){
				let that = this;
				let param = {};
				param.title = title;
				// #ifdef MP-WEIXIN
				if(this.is_visit){
					wx.chooseLocation({
						success (res) {
							const address = res.address;
							let reg = /.+?(省|市|自治区|自治州|县|区)/g;
							let city = address.match(reg)[1];
							const name = res.name;
							const latitude = res.latitude; //纬度
							const longitude = res.longitude; //经度
							isCityOpen({city_name: city}).then((res)=>{
								if(type==1){// 选择取车城市、地点
									that.area.city_name = city;
									that.area.area_name = name;
									that.area.area_id = 0;
									that.area.city_id = res.data.id;
									that.area.latitude = latitude;
									that.area.longitude = longitude;
								}else{// 选择还车城市、地点
									that.area.black_city_name = city;
									that.area.black_area_name = name;
									that.area.black_city_id = res.data.id;
									that.area.black_area_id = 0;
									that.area.black_latitude = latitude;
									that.area.black_longitude = longitude;					
								}
								that.area.is_other_places = that.is_other_places;
								that.area.is_visit = that.is_visit;
								uni.setStorageSync('ADDRESS',that.area)
							}).catch((err)=>{
								return uni.showToast({ title:err, icon:'none' })
							})
						}
					})
					return;
				}
				//#endif
				if(type == 1){
					if(!that.area.city_id) return uni.showToast({title:'请选择取车城市',icon:"none"})
					param.name = that.area.city_name;
					param.id = that.area.city_id;
				}else{
					if(!that.area.black_city_id) return uni.showToast({title:'请选择还车城市',icon:"none"})
					param.name = that.area.black_city_name;
					param.id = that.area.black_city_id;
				}
				uni.navigateTo({
					url:`/pages/car_sub/address_list/index?param=${JSON.stringify(param)}`,
					events:{
						getAddress(option){
							if(type == 1){// 选择取车城市
								that.area.area_name = option.title;
								that.area.area_id = option.id;
								that.area.latitude = option.latitude;
								that.area.longitude = option.longitude;
							}else{// 选择还车城市
								that.area.black_area_name = option.title;
								that.area.black_area_id = option.id;
								that.area.black_latitude = option.latitude;
								that.area.black_longitude = option.longitude;
							}
							that.area.is_other_places = that.is_other_places;
							that.area.is_visit = that.is_visit;
							uni.setStorageSync('ADDRESS',that.area)
						},
					},
				})
			},
			//展示取车、还车弹窗
			showTimePicker(type,nav_type){ // 0取车  1还车
				this.$refs.nav_type = nav_type;
				this.$refs.timePicker.picker_modal = true;
				this.$refs.timePicker.time_type = type;
				this.$refs.timePicker.getDay(210);
				this.$refs.timePicker.calTimes();
				if(this.DateTime.start_time){
					this.$refs.timePicker.start_time = this.DateTime.start_time;
					this.$refs.timePicker.end_time = this.DateTime.end_time;
				}
			},
			//获取取车、还车时间
			getTime(date){
				this.DateTime.start_time = date.starTime.starTime;
				this.DateTime.end_time = date.endTime.endTime;
				this.DateTime.starDay = date.starTime.date.date;
				this.DateTime.endDay = date.endTime.date.date;
				this.DateTime.starTime = date.starTime.time;
				this.DateTime.endTime = date.endTime.time;
				this.DateTime.starMon = date.starTime.date.month;
				this.DateTime.endMon = date.endTime.date.month;
				let endList = date.endTime.time.split(':');//分割时间
				this.DateTime.endStamp = new Date(date.endTime.date.year, (date.endTime.date.month-1), date.endTime.date.date).getTime();
				let starList = date.starTime.time.split(':');//分割时间
				this.DateTime.starStamp = new Date(date.starTime.date.year, (date.starTime.date.month-1), date.starTime.date.date).getTime();
				let diffDate = this.happenTimeFun(this.DateTime);
				this.DateTime.days = diffDate.value;
				this.DateTime.day = diffDate.day;
				this.DateTime.hour = diffDate.hour;
				this.$refs.timePicker.picker_modal = false;
			},
			// 立即选车
			toChooseCar(param){
				if(!this.area.city_name) return uni.showToast({title:'请选择取车城市',icon:'none'})
				if(!this.area.area_name) return uni.showToast({title:'请选择取车地点',icon:'none'})
				param.city_id = param.black_city_id = this.area.city_id ;
				param.area_id = param.black_area_id = this.area.area_id ;
				param.city_name = param.black_city_name = this.area.city_name ;
				param.area_name = param.black_area_name = this.area.area_name ;
				param.is_other_places = this.is_other_places;
				if(this.is_other_places){
					if(!this.area.black_city_name) return uni.showToast({title:'请选择还车城市',icon:'none'})
					if(!this.area.black_area_name) return uni.showToast({title:'请选择还车地点',icon:'none'})
					param.black_city_id = this.area.black_city_id ;
					param.black_area_id = this.area.black_area_id ;
					param.black_city_name = this.area.black_city_name ;
					param.black_area_name = this.area.black_area_name ;
				}

				param.is_visit = this.is_visit;
				if(!this.is_visit){
					param.black_latitude = param.take_latitude =  this.area.latitude;
					param.black_longitude = param.take_longitude = this.area.longitude;
				}else{
					param.black_latitude = this.area.black_latitude ? this.area.black_latitude : '' ;
					param.black_longitude = this.area.black_longitude ? this.area.black_longitude : '' ;
					param.take_latitude = this.area.latitude ? this.area.latitude : '' ;
					param.take_longitude = this.area.longitude ? this.area.longitude : '' ;
				}

        const vehModeConf = this.vehModeConf;
				param = { ...param, ...vehModeConf };

        param.areaInfo = this.area;

        this.closeVehConfig();
        
				disposeTime(param).then((res)=>{
          this.$emit('change', {
            param: JSON.stringify(param),
            date: JSON.stringify(res.data)
          })
				}).catch((err)=>{
					uni.showToast({title:err,icon:'none'})
				})
			},
			// 获取当天日期、时间
			getCurDate(){
				let date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let curDay = date.getDate();
				let curHours = date.getHours();
				let curMin =  date.getMinutes();
				this.DateTime.starStamp = new Date(year,(month-1), curDay).getTime();
				this.DateTime.starMon = month < 10? '0'+month:month;
				this.DateTime.starDay = curDay< 10? '0'+curDay:curDay;
				if(curMin > 30) curHours = curHours+1;
				this.DateTime.starTime = this.DateTime.endTime = ( curHours < 10? '0' + curHours : curHours )+ ':' + ( curMin < 30 ? '30' : '00' );
				let tomDate = date.setDate(date.getDate()+1); //获取1天后的 时间戳
				let tom = new Date(tomDate);
				let tomYear = tom.getFullYear();
				let tomMon = tom.getMonth() + 1;
				let tomDay = tom.getDate();
				this.DateTime.endStamp = new Date(tomYear,(tomMon-1), tomDay).getTime();
				this.DateTime.endMon = tomMon < 10? '0'+tomMon:tomMon;
				this.DateTime.endDay = tomDay < 10? '0'+tomDay:tomDay;
			},
			// 计算用车时间
			happenTimeFun(time){
				let star_date = new Date(time.starStamp);
				let end_date = new Date(time.endStamp);
				let star_year = star_date.getFullYear();
				let end_year = end_date.getFullYear();
				let star_month = star_date.getMonth() + 1;
				let end_month = end_date.getMonth() + 1;
				star_month = star_month < 10 ? ('0'+star_month) : star_month;
				end_month = end_month < 10 ? ('0'+end_month) : end_month;
				let star_day = star_date.getDate();
				let end_day = end_date.getDate();
				star_day = star_day < 10 ? ('0'+star_day) : star_day;
				end_day = end_day < 10 ? ('0'+end_day) : end_day;
				let star_time = star_year+'-'+star_month+'-'+star_day+' '+time.starTime+':00';
				let end_time = end_year+'-'+end_month+'-'+end_day+' '+time.endTime+':00';
				let star_timestamp = new Date(star_time).getTime()/1000;
				let end_timestamp = new Date(end_time).getTime()/1000;
				let difference = (end_timestamp - star_timestamp)/3600;
				let day = 0;
				let hour = 0;
				let sum = difference;
				for(let i = 0;i < difference; i++){
					if(sum >= 24){
						sum = sum - 24;
						day++;
					}else{
						hour = sum;
						break;
					}
				}
				if(hour > 0){
					if(day > 0){
						return {
							value:day+'天'+hour+'小时',
							day:day,
							hour:hour
						}
					}else{
						return {
							value:hour+'小时',
							day:day,
							hour:hour
						}
					}
				} else {
					return {
						value:day+'天',
						day:day,
						hour:hour
					}
				}
			}
		},
	}
</script>

<style scoped lang="scss">
.address-time-picker {
  margin: 24rpx 32rpx;
  padding: 16rpx;
  background: #F8F9FC;
  border-radius: 24rpx;
  position: relative;
  .store_name {
    line-height: 44rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 28rpx;
    color: rgba(0,0,0,0.9);
    text-align: center;
  }
  .hire_time {
    margin-top: 8rpx;
    height: 44rpx;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: rgba(0, 0, 0, 0.9);
    .line {
      width: 40rpx;
      flex: 0 0 40rpx;
      height: 2rpx;
      background: #E7E7E7;
      border-radius: 0px 0px 0px 0px;
      margin: 0 16rpx;
    }
  }
  .edit-icon {
    position: absolute;
    right: 32rpx;
    top: 46rpx;
    width: 36rpx;
    height: 36rpx;
  }
}
.popup-container {
  padding: 32rpx;
  padding-top: 40rpx;
  .picker-row {
    margin-bottom: 40rpx;
    .picker-row-title {
      margin-bottom: 40rpx;
      color: rgba(0,0,0,0.6);
      height: 44rpx;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 48rpx;
    }
    .picker-row-content {
      font-weight: 600rpx;
      height: 48rpx;
      font-size: 32rpx;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 60rpx;
      .address {
        width: 450px;
        flex: 0 0 450rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
	.select-time {
    background: #F8F9FC;
    border-radius: 24rpx;
    padding: 16rpx 42rpx;
	}
}

.container-page {
	color: rgba(0, 0, 0, 0.9);
}
.only_filter {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 24rpx;
  font-size: 28rpx;
  .text {
    color: rgba(0,0,0,0.4);
  }
}

.center_box {
	padding: 30rpx;
	border: 4rpx solid #FFFFFF;
	border-radius: 20rpx;
	background: linear-gradient(180deg, #FAFAFE 0%, #E7F6FE 100%);

	.selection {
		display: flex;
		align-items: center;
		justify-content: center;
		line-height: 48rpx;
		font-size: 32rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		justify-content: flex-start;
		color: rgba(0, 0, 0, 0.9);
		.selection_icon {
			flex: 0 0 32rpx;
			width: 32rpx;
			height: 32rpx;
			margin-left: 4rpx;
		}
	}
}




.btn-tips{
	border-radius: 8rpx;
	padding:3rpx 5rpx;
	border:2rpx solid #F03838;
	color: #F03838;
	font-size: 22rpx;
}
.grid-nav{
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 20rpx;
}
button::after{
	content: '';
	border: none;
}
.index-nav {
	width: 100%;
	// padding-left: 10rpx;
	// padding-right: 10rpx;
	margin-top: 10rpx;
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
}


._column-box-two{
	display: inline-block;
	// display: flex;
	// flex-wrap: wrap;
	// justify-content: space-between;
	-moz-column-count:2; /* Firefox */
    -webkit-column-count:2; /* Safari 和 Chrome */
	column-count:2;
	-moz-column-gap: 30rpx;
    -webkit-column-gap: 30rpx;
    column-gap: 30rpx;
	& .item{
		-webkit-column-break-inside: avoid;
		break-inside: avoid; /*防止断点*/
		width: 100%;
		margin: 25rpx 0;
	}
	
	
	& .item:nth-child(2n){
		float: right;
		height: 100%;
	}
	& .item:nth-child(2n-1){
		float: left;
		height: 420rpx;
	}
	& .item:nth-child(1){
		margin-top: 0;
	}
	
}
.column-bg{
	background-image: url('https://uxcar.uxphp.net/uploads/attach/2023/07/20230731/2c3b0e5a3f09cb437f5515419f8109b5.png');
	background-size: 100% 100%;
	background-repeat: no-repeat;
	vertical-align: bottom;
}

.coupon-item{
	border: 2rpx solid #FF7029;
	background-color: rgba(255, 112, 41, 0.1);
	color: #FF7029;
	position: relative;
	border-radius: 16rpx;
}

.coupon-item-had{
	border: 2rpx solid #999;
	background-color: rgba(0,0,0,0.1);
	color: #999;
	position: relative;
	border-radius: 16rpx;
}
</style>